<template>
  <div>
    <div>
      <el-input style="width: 200px" placeholder="查询用户名" v-model="username"></el-input>
      <el-input style="width: 200px;margin:0 15px" placeholder="查询姓名" v-model="name"></el-input>
      <el-button type="primary" @click="load(1)" plain>查询</el-button>
      <el-button type="primary" @click="reset" plain>重置</el-button>
    </div>
    <div style="margin: 10px 0">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="doubleDelete">批量删除</el-button>
    </div>
    <el-table :data="tableData" stripe :header-cell-style="{backgroundColor:'aliceblue',color:'#666'}"@selection-change="handleSelectChange">
      <el-table-column type="selection" width="55" align="center">
      </el-table-column>
      <el-table-column label="ID" prop="id"></el-table-column>
      <el-table-column label="用户名" prop="username"></el-table-column>
      <el-table-column label="姓名" prop="name"></el-table-column>
      <el-table-column label="手机号" prop="phone"></el-table-column>
      <el-table-column label="Email" prop="email"></el-table-column>
      <el-table-column label="地址" prop="address"></el-table-column>
      <el-table-column label="头像">
        <template v-slot="scope">
          <div v-if="scope.row.avatar">
            <el-image :src="scope.row.avatar" style="width: 50px; height: 50px;border-radius: 50%"
                      :preview-src-list="[scope.row.avatar]"></el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="角色" prop="role"></el-table-column>
      <el-table-column label="操作" align="center" width="180px">
        <template v-slot="scope">
          <div>
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger"@click="del(scope.row.id)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin:10px 0">
      <el-pagination
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-size="pageSize"
          layout="total,prev, pager, next"
          :total="total">
      </el-pagination>
    </div>
    <el-dialog title="用户信息"  :visible.sync="formVisible" width="30%">
      <el-form :model="form" label-width="80px" style="padding-right: 50px" :rules="rules" ref="formRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input type="textarea" v-model="form.address"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-radio-group v-model="form.role">
            <el-radio label="管理员"></el-radio>
            <el-radio label="用户"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:9090/file/upload"
              :headers="{token: user.token}"
              list-type="picture"
              :on-success="handAvatarSuccess"
          >
            <el-button type="primary" plain>上传头像</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formVisible = false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  name: "User",
  data() {
    return {
      user: JSON.parse(localStorage.getItem('base-user') || '{}'),
      tableData: [],//所有数据
      pageNum: 1,//当前页码
      pageSize: 6,//每页显示个数
      username: '',
      name: '',
      total: 0,
      formVisible: false,
      form: {},
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 8, max: 20, message: '用户名长度应在8到20个字符之间', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9_-]+$/, message: '用户名不能包含特殊字符', trigger: 'blur' },
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 5, message: '姓名长度应在2到5个字符之间', trigger: 'blur' },
          { pattern: /^[\u4e00-\u9fa5]+$/, message: '请输入有效的中文姓名', trigger: 'blur' } // 仅允许中文
        ],
        phone: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' } // 中国手机号格式
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入有效的邮箱地址', trigger: ['blur', 'change'] }
        ],
        address: [
          { required: true, message: '请输入地址', trigger: 'blur' },
          { min: 5, message: '地址长度不能少于5个字符', trigger: 'blur' } // 简单的长度验证
        ],
        role: [
          { required: true, message: '请选择角色', trigger: 'change' } // 确保用户选择了一个角色
        ]
      },
      ids:[]
    }
  },
  created() {
    this.load()
  },
  methods: {
    doubleDelete(){
      if(!this.ids.length){
        this.$message.warning("请选择数据")
        return
      }
      if(!this.ids.includes(this.user.id)){
        this.$confirm("确认批量删除这些数据么","确认删除",{type:"warning"}).then(response =>{
          this.$request.delete('/user/delete/double',{data:this.ids}).then(res =>{
            if(res.code === "200"){//操作成功
              this.$message.success("操作成功")
              this.load(1)
            }else{
              this.$message.error(res.msg)
            }
          })
        }).catch(()=>{})
      }else{
        this.$message.error("包含当前用户，不允许自我删除")
      }
    },
    handleSelectChange(rows){
      this.ids = rows.map(v => v.id)
    },
    del(id){
      if(id !== this.user.id){
        this.$confirm("确认删除么","确认删除",{type:"warning"}).then(response =>{
          this.$request.delete('/user/delete/'+id).then(res =>{
            if(res.code === "200"){//操作成功
              this.$message.success("操作成功")
              this.load(1)
            }else{
              this.$message.error(res.msg)
            }
          })
        }).catch(()=>{})
      }else{
        this.$message.error("不允许用户自我删除")
      }
    },
    handleEdit(row) {//编辑数据
      this.form = JSON.parse(JSON.stringify(row)) //给form对象赋值，注意要深拷贝数据
      this.formVisible = true
    },
    handleAdd() {//新增数据
      this.form = {role:'用户'}//点击新增数据的时候首先清空表并默认角色为用户
      this.formVisible = true//打开弹窗
    },
    save() { //保存按钮触发逻辑，触发新增或更新
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.$request({
            url:this.form.id ? '/user/update':'/user/add',
            method:this.form.id ? 'PUT':'POST',
            data:this.form
          }).then(res => {
            if(res.code === '200'){
              this.$message.success('保存成功')
              this.load(1)
              this.formVisible = false
            }else{
              this.$message.error(res.msg)//输出错误信息
            }
          })
        }
      })
    },
    reset() {
      this.name = ''
      this.username = ''
      this.load()
    },
    handleCurrentChange(pageNum) {
      this.load(pageNum)
    },
    load(pageNum) {  //分页查询
      if (pageNum) this.pageNum = pageNum
      this.$request.get('/user/selectByPage', {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          username: this.username,
          name: this.name,
        }
      }).then(res => {
        // 检查 res.data 是否存在且不为 null
        if (res.data && res.data.records) {
          this.tableData = res.data.records;
          this.total = res.data.total;
        } else {
          // 如果 res.data 不存在或 res.data.records 不存在，则处理错误情况
          console.error('未获取到有效数据:', res);
          // 可以选择清空 tableData 和 total，或者显示错误消息给用户
          this.tableData = [];
          this.total = 0;
        }
      }).catch(error => {
        // 处理请求失败的情况
        console.error('加载数据失败:', error);
        // 同样，可以选择清空 tableData 和 total，或者显示错误消息给用户
        this.tableData = [];
        this.total = 0;
      });
    },
    handleTableFileUpload(row, file, fileList) {
      row.avatar = file.response.data
      // this.$set(row,'avatar',file.response.data) //强制设置
      //触发更新
      request.put('/user/update', row).then(res => {
        if (res.code === '200') {
          this.$message.success('上传成功')
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    handAvatarSuccess(response, file, fileList) {
      this.form.avatar = response.data
    },
  }
}
</script>

<style scoped>

</style>